package com.oocl.thread;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.chat.dao.impl.UserOperateImpl;
import com.oocl.chat.dao.impl.WorkOperateImpl;
import com.oocl.chat.pojo.Message;
/**
 * 工作线程
 * @author Evan Huang
 *
 */
public class SocketListener implements Runnable{
	private Socket socket;
	private BufferedReader reader;
	private BufferedWriter writer;
	private boolean quit = false;
	WorkOperateImpl work = new WorkOperateImpl();
//	UserOperateImpl uOpearate = new UserOperateImpl();

	public SocketListener(Socket socket) throws Exception {
		super();
		this.socket = socket;
		this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
	}
	public BufferedReader getreader() {
		return reader;
	}
	public BufferedWriter getwriter() {
		return writer;
	}
	
	public void run() {
		while(!quit){
			try {
				begin();
			}catch (Exception e) {
				System.out.println("断开连接");
				quit = true;
			}
		}
	}
	public void begin() throws ClassNotFoundException, IOException{
		Message message = null;
		ObjectMapper mapper = new ObjectMapper();
		String m = null;
		if((m = reader.readLine())!=null){
			message = mapper.readValue(m, Message.class);
			int type = message.getType();
			switch(type){
			case 0:
				work.chat(message,writer);
				break;
			case 1:
				work.shake(message,writer);
				break;
			case 2:
				work.online(message,writer);
				break;
			case 3:
				work.downline(message,writer);
				quit = true;
				closeFlow();
			case 6:
				work.register(message,writer);
				break;
			}
		}
	}

	private void closeFlow(){
		try {
			socket.close();
		} catch (IOException e) {
			System.out.println("close??");
		}
	}
}
